package org.musicguardian.core;

import java.io.File;
import java.io.IOException;

import org.musicguardian.core.model.Library;
import org.musicguardian.core.model.Model;
import org.musicguardian.core.scan.Scanner.ScannerListener;
import org.prevayler.Prevayler;
import org.prevayler.PrevaylerFactory;
import org.prevayler.TransactionWithQuery;
import org.prevayler.implementation.snapshot.XmlSnapshotManager;

public class Core {

	public final static String DATA_FOLDER = "data";

	private static Core musicGuardian = null;

	private Prevayler prevayler;

	private Core() throws ClassNotFoundException, IOException {
		super();
		initializePrevaler();
	}

	public static Core getInstance() {
		if (musicGuardian == null) {
			try {
				musicGuardian = new Core();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return musicGuardian;
	}

	private void initializePrevaler() throws ClassNotFoundException,
			IOException {
		PrevaylerFactory factory = new PrevaylerFactory();
		factory.configurePrevalenceBase(DATA_FOLDER);
		factory.configureSnapshotManager(new XmlSnapshotManager(new Model(),
				DATA_FOLDER));
		prevayler = factory.create();
		Thread snapShotThread = new Thread() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(50000);
						prevayler.takeSnapshot();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		};
		//snapShotThread.start();
	}
	
	public Model getModel(){
		return (Model) prevayler.prevalentSystem();
	}

	public void runTransaction(TransactionWithQuery transaction) throws Exception {
		prevayler.execute(transaction);
	}
}
